import logging
import sys

from robot.utils.argumentparser import ArgumentParser

logger = logging.getLogger("RobotArgumentParser")
from robot.run import USAGE


class RobotArgumentParser():
    def __init__(self, args=None):
        self._parse_args(args)

    def _parse_args(self, args=None):
        """
        调用robot封装的参数解析类，获取robot设置参数
        :param args: 命令参数，如果未传入，从命令行获取
        :return: opts:robot参数信息; args:参数list
        """
        argvs = args
        if argvs == None:
            argvs = sys.argv[1:]
        try:
            argumentParser = ArgumentParser(USAGE, arg_limits=(1,))
            self.opt, self.args = argumentParser.parse_args(argvs)
            logger.info('opt %s', self.opt)
        except:
            logger.error("get argument error", exc_info=1)

    def getZCMVariableValue(self, key) -> str:
        """
        -v key:value 获取value值，key不存在，或者格式不对，都返回None
        :param key:
        :return:
        """
        for vars in self.opt['variable']:
            if str(vars).startswith(key):
                zcmvar = str(vars)
                # print(zcmvar)
                # print(len(zcmvar))
                if len(zcmvar) > zcmvar.index(':') + 1:
                    return zcmvar[zcmvar.index(':') + 1:]
        return None

    def zcmVariableExist(self, key) -> str:
        """
        -v key 该key值是否存在，全匹配，区分大小写
        :param key:
        :return:
        """
        for vars in self.opt['variable']:
            if str(vars) == key:
                return True
        return False


if __name__ == '__main__':
    argvs = ['--pythonpath', 'E:\\ZCM\\devspace\\code\\zcmtest2', '--pythonpath',
             'E:/ZCM/devspace/code/zcm-cloudtest-agent', '-v', 'zprofile:dev', '-v', 'xxxx', '--listener',
             'E:/ZCM/devspace/code/zcm-cloudtest-agent/zcm/listener/ZTestRunnerAgent.py', '-d',
             'E:\\ZCM\\devspace\\code\\zcmtest2\\log', '--dryrun', './']
    rap = RobotArgumentParser(argvs)
    print(rap.getZCMVariableValue('zprofile'))
